package com.by.basicgateway.security;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson2.JSON;
import com.by.basicgateway.dto.ByGatewayAuthentication;
import com.by.basicgateway.enums.RequestorClientTypeEnum;
import com.by.toolkit.consts.WebGlobalConst;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.authorization.AuthorizationDecision;
import org.springframework.security.authorization.ReactiveAuthorizationManager;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.server.authorization.AuthorizationContext;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Mono;

import java.util.Map;
import java.util.Objects;


/**
 * 判断用户权限
 *
 * @author Tian Wei
 * @version 1.0
 * @date 2023/12/21 4:13 PM
 */
@Slf4j
@Component
public class UserAuthorizationManager implements ReactiveAuthorizationManager<AuthorizationContext> {

    @Override
    public Mono<AuthorizationDecision> check(Mono<Authentication> authenticationMono, AuthorizationContext authorizationContext) {
        return authenticationMono.map(oriAuthentication -> {
            ByGatewayAuthentication authentication = (ByGatewayAuthentication) oriAuthentication;
            String token = authentication.getCredentials();
            if (StringUtils.isEmpty(token)) {
                log.info("[UserAuthorizationManager][check] 用户认证信息:token不存在:{}", JSON.toJSONString(authenticationMono));
                return new AuthorizationDecision(false);
            }
            Long userId = authentication.getPrincipal();
            if (Objects.isNull(userId)) {
                log.info("[UserAuthorizationManager][check] 用户认证信息:userId不存在,认证信息为:{}", JSON.toJSONString(authenticationMono));
                return new AuthorizationDecision(false);
            }

            Map<String, String> userContentMap = authentication.getDetails();
            if (CollectionUtil.isEmpty(userContentMap)) {
                log.info("[UserAuthorizationManager][check]  用户认证信息:用户详情信息不存在,认证信息为:{}", JSON.toJSONString(authenticationMono));
                return new AuthorizationDecision(false);

            }
            return new AuthorizationDecision(true);
        }).defaultIfEmpty(new AuthorizationDecision(true));

    }
}